library(countrycode)
library(haven)
library(ggplot2)
library(tidyr)
library(dplyr)
library(stringr)

setwd("C:/Users/jonves/Dropbox/Papers/SSP-Instability-Opinion/replication_data/")

growth <- function(x){x/lag(x)-1}

#### Economic growth ####

pwt <- read_dta("data/pwt90.dta")
pwt$gdpcap <- pwt$rgdpna / pwt$pop

pwt <- group_by(pwt, countrycode) %>%
  arrange(year) %>%
  mutate(grwt = growth(gdpcap),
         grwt_rgdpna = growth(rgdpna)) %>%
  select(countrycode, year, gdpcap, grwt, grwt_rgdpna)


#### Regime type, VDem Regimes of the World ###
vdem <- read_dta("data/vdem_stata_ic_v8/V-Dem-CY-IC-v8.dta", encoding = "latin1")
names(vdem)

vdem <- select(vdem, country_name, country_id, country_text_id, year, v2x_regime, v2x_libdem, v2x_polyarchy, v2x_partipdem,
               v2x_delibdem, v2x_egaldem)
vdem <- select(vdem, country_name, country_id, country_text_id, year, v2x_regime)

#### Merge ####
df <- left_join(pwt, vdem, by=c("countrycode" = "country_text_id", "year" = "year")) %>% arrange(countrycode, year)
df <- na.omit(df)
df$v2x_regimef <- factor(df$v2x_regime, labels=c("Closed Autocracy", "Electoral Autocracy", "Electoral Democracy", "Liberal Democracy"))

m1 <- lm(grwt ~ v2x_regime + gdpcap, data=df)

# Suspect big growth rates are due to measurement errors (rebasing, etc.)
df$grwt_c <- if_else(df$grwt > 0.10, 0.10, df$grwt) 
df$grwt_c <- if_else(df$grwt < -0.10, -0.10, df$grwt_c)

agg <- group_by(df, v2x_regimef) %>%
  summarize(ngrwtr = mean(grwt_c < 0, na.rm = T),
            hgrwtr = mean(grwt_c > 0.07, na.rm = T),
            agrwtr = mean(grwt_c, na.rm = T))

agg$ngrwtr_text <- paste("Neg. gr. r.:",round(agg$ngrwtr, 2)*100, "%")

p1 <- ggplot(df, aes(x=v2x_regimef, y=grwt_c)) + 
  geom_violin(draw_quantiles = c(0.5)) + geom_hline(yintercept=0, size=1) +
  geom_text(data=agg, aes(x=v2x_regimef, y=-0.025, label=ngrwtr_text), size=2.9) +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
  coord_flip() +
  xlab("V-Dem regimes of the world") +
  ylab("PWT 9.0 GDP/capita growth") +
  theme_bw() +
  theme(strip.text.x = element_text(size=14),
        axis.title = element_text(size=14),
        axis.text = element_text(size=14))

ggsave("results/figure4b.tiff", plot=p1, width=6, height=6, dpi=300, compression="zip")